<script setup lang="ts">
import { ref, computed, watchEffect } from 'vue'
import { deepClone } from '@/utils/index'
import SytTableColumn from './SytTableColumn.vue'

const props = defineProps({
  columns: {
    type: Array as any,
    default: () => []
  },
  data: {
    type: Array as any,
    default: () => []
  },
  selection: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['selection-alter'])
let tableRef = ref()

let tableThArr = computed<any>(() => props.columns)
let tableData = ref([])
//保存排序类型 data响应后维持排序
let columnName = ref('')
let orderType = ref('')

//排序
let sortTable = ({ prop, order }) => {
  columnName.value = prop
  orderType.value = order
  if (order === 'ascending') {
    tableData.value.sort((a, b) => {
      if (a[prop] < b[prop]) return 1
      if (a[prop] > b[prop]) return -1
      return 0
    })
  }
  if (order === 'descending') {
    tableData.value.sort((a, b) => {
      if (a[prop] < b[prop]) return -1
      if (a[prop] > b[prop]) return 1
      return 0
    })
  }
}

watchEffect(() => {
  tableData.value = deepClone(props.data)
  sortTable({ prop: columnName.value, order: orderType.value })
})

let pageSize = ref(10)
let currentPage = ref(1)

let currentTableData = computed(() => {
  let start = (currentPage.value - 1) * pageSize.value
  let end = start + pageSize.value
  return tableData.value.slice(start, end)
})

const handleSelectionChange = (val) => {
  emit('selection-alter', val)
}
</script>

<template>
  <div>
    <el-table
      ref="tableRef"
      :data="currentTableData"
      row-key="_id"
      max-height="80%"
      border
      stripe
      @sort-change="sortTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="selection" :type="'selection'" reserve-selection :width="55" />
      <SytTableColumn v-for="item of tableThArr" :key="item.dataIndex" :th-data="item" />
      <el-table-column label="操作" align="center" fixed="right" :width="100">
        <template #default="{ row, column, $index }">
          <slot name="operations" :row="row" :column="column" :$index="$index" />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:page-size="pageSize"
      v-model:current-page="currentPage"
      small
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      :page-sizes="[10, 20, 30, 40, 50, 100]"
      class="pagination"
    />
  </div>
</template>

<style scoped>
.pagination {
  margin-top: 10px;
}
</style>
